import {
    getUserDetailReq,
    getFollowingReq,
    checkInReq,
    cancelFollowReq,
    addFollowReq,
    realInfoVerifyReq,
    withdrawReq,
    withdrawLogsReq,
    saveAccountInfoReq,
    fetchConsumeDataReq,
    applyStarReq,
    resetPasswordReq,
    changeNameReq,
    fetchOfficialNoticeReq,
    fetchAccountInfoReq,
    fetchPayDataReq,
    fetchSystemInfoReq,
    fetchCoinConsumeLogReq,
    fetchItemConsumeLogReq,
    uploadAvatarReq,
    buyVipReq,
    feedbackReq,
    wechatReq,
    checkWechatOrderReq,
    forgetPasswordReq,
    feedbackListReq
} from "../apis/goApis"
import React from 'react'

import {handleResp,} from "../utils/commonfunc"
import {encryptPwd} from '../utils/encryptService'
import LocalStorageService from "../utils/LocalStorageService";
import {Toast} from "antd-mobile";
import {magic,} from "../utils/constants";
const uid = LocalStorageService.get('userid')

const defaultUserdetail = {
    "Email": "",
    "Exp": 0,
    "Gender": 1,
    "Gold": 0,
    "Iconurl": '',
    "Id": "",
    "IsShowing": false,
    "IsStar": false,
    "Mobile": '',
    "Nickname": '',
    "Pwd": '',
    "Realname": '',
    "Username": '',
    "Tokenuuid": '',
    "Viplevel": 0,
    "Wxid": "",
    "Packet": "[]",
    initFlag: 0,
    "Vip": 0,
    "Vipst": 0,
    "Supervip": 0,
    "Supervipst": 0,
}

const defaultCheckinInfo = {
    'seq': 0,
    'signtoday': false,
}

export const user = {
    state: {
        userdetail: defaultUserdetail,
        checkinInfo: defaultCheckinInfo,
        following: {
            1: [
                {
                    Who: '',
                }
            ],
        },
        coinConsumeList: [],
        itemConsumeList: [],
        depositList: [],
        feedback: {},
        feedbackList: [],
    },

    reducers: {
        setUserDetail(state, payload) {
            payload.initFlag = 1
            payload.Iconurl = payload.Iconurl + '#' + Math.random()
            return {
                ...state,
                userdetail: payload,
            }
        },

        setCheckinInfo(state, payload) {
            return {
                ...state,
                checkinInfo: payload,
            }
        },

        checkinToday(state, payload) {
            return {
                ...state,
                checkinInfo: {
                    'seq': payload.Seqdays,
                    'signtoday': payload.Signtoday,
                },
            }
        },
        onLogout(state, payload) {
            return {
                ...state,
                userdetail: defaultUserdetail,
                checkinInfo: defaultCheckinInfo,
            }
        },
        onChangeName(state, payload) {
            return {
                ...state,
                userdetail: {
                    ...state.userdetail,
                    "Nickname": payload.newnick,
                }
            }
        },

        setFollowingList(state, payload) {
            return {
                ...state,
                following: {1: payload.ok.data},
            }
        },

        setCoinConsumeList(state, payload) {
            return {
                ...state,
                coinConsumeList: [
                    ...state.coinConsumeList,
                    ...payload.list,
                ]
            }
        },

        setCoinConsumeListEmpty(state, payload) {
            return {
                ...state,
                coinConsumeList: []
            }
        },

        setItemConsumeList(state, payload) {
            return {
                ...state,
                itemConsumeList: [
                    ...state.itemConsumeList,
                    ...payload.list,
                ]
            }
        },

        setItemConsumeListEmpty(state, payload) {
            return {
                ...state,
                itemConsumeList: []
            }
        },

        setDepositList(state, payload) {
            return {
                ...state,
                depositList: [
                    ...state.depositList,
                    ...payload.list,
                ]
            }
        },

        setDepositListEmpty(state, payload) {
            return {
                ...state,
                depositList: []
            }
        },

        setFeedbackList(state, payload) {
            return {
                ...state,
                feedbackList: payload,
            }
        }

    },

    effects: (dispatch) => ({

        fetchUserDetail(payload, rootState,) {

            const promise = new Promise((resolve => {

                const resp = getUserDetailReq(payload, false)
                resp.then(resp => {

                    handleResp(resp, dispatch, (data) => {
                        if (data.ok) {
                            dispatch.user.setUserDetail(data.ok)
                            dispatch.user.setCheckinInfo(data.signquest)
                            resolve(true)
                        } else {
                            resolve(false)
                        }
                    })
                })

            }))

            return promise
        },

        async fetchFollowList(payload, rootState) {
            const resp = await getFollowingReq({uid: payload, p: 1,})
            handleResp(resp, dispatch, (data) => {
                dispatch.user.setFollowingList(data)
            })
        },

        async doCheckin(payload, rootState) {
            const resp = await checkInReq({uid: payload})
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const addexp = data.addexp
                    const info = <div>
                        <p>签到成功</p>
                        <p>经验+{addexp}</p>
                    </div>

                    Toast.info(info, 1)

                    dispatch.user.checkinToday(data.ok)
                }

            })
        },

        async doCancelFollow(payload, rootState) {
            const resp = await cancelFollowReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok.del) {
                    const uid = localStorage.getItem('userid')
                    dispatch.user.fetchFollowList(uid)
                }
            })
        },

        async doAddFollow(payload, rootState) {

            const resp = await addFollowReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok.add) {
                    const uid = localStorage.getItem('userid')
                    dispatch.user.fetchFollowList(uid)
                }
            })
        },

        async doRealInfoVerify(payload, rootState) {
            const resp = await realInfoVerifyReq({
                uid: payload.uid,
                rn: payload.realName,
                in: payload.idNumber,
                m: payload.mobile,
                c: payload.code,
            })

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const uid = localStorage.getItem('userid')
                    dispatch.user.fetchUserDetail({uid,})
                    const addExp = data.addexp
                    const info = <div>
                        <p>认证成功</p>
                        <p>经验+{addExp}</p>
                    </div>
                    Toast.info(info, 1,)
                }
            })
            return resp
        },

        async doWithdraw(payload, rootState) {
            const resp = await withdrawReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doWithdrawLogs(payload, rootState) {
            const resp = await withdrawLogsReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doFetchAccountInfo(payload, rootState) {
            const resp = await fetchAccountInfoReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doSubmitAccountInfo(payload, rootState) {
            const resp = await saveAccountInfoReq({
                who: payload.uid,
                card: payload.bankCard,
                bank: payload.bank[0],
                sub: payload.district[0],
                subname: payload.subbranch,
                receiver: payload.realName,
                idnumber: payload.idNumber,
                mobile: payload.mobile,
            })
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doFetchConsumeData(payload, rootState) {
            const resp = await fetchConsumeDataReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doFetchCoinConsumeLog(payload, rootState) {
            const resp = await fetchCoinConsumeLogReq({uid: payload.uid, p: payload.p,})
            handleResp(resp, dispatch, (data) => {
                const p = payload
                const list = data.ok.data
                if (list.length === 0) {
                    if (payload.endCallback) {
                        payload.endCallback()
                    }

                }
                dispatch.user.setCoinConsumeList({p, list})
            })
        },

        doEmptyConsumeList(payload, rootState) {
            dispatch.user.setCoinConsumeListEmpty()
        },

        async doFetchItemConsumeLog(payload, rootState) {
            const resp = await fetchItemConsumeLogReq({uid: payload.uid, p: payload.p,})
            handleResp(resp, dispatch, (data) => {
                const p = payload
                const list = data.ok.data
                if (list.length === 0) {
                    if (payload.endCallback) {
                        payload.endCallback()
                    }
                }
                dispatch.user.setItemConsumeList({p, list})
            })
        },

        doEmptyItemConsumeList(payload, rootState) {
            dispatch.user.setItemConsumeListEmpty()
        },

        async doDepositList(payload, rootState) {
            const resp = await fetchPayDataReq({uid: payload.uid, p: payload.p,})
            handleResp(resp, dispatch, (data) => {
                const p = payload
                const list = data.ok.data
                if (list.length === 0) {
                    if (payload.endCallback) {
                        payload.endCallback()
                    }
                }
                dispatch.user.setDepositList({p, list})
            })
        },

        doEmptyDepositList(payload, rootState) {
            dispatch.user.setDepositListEmpty()
        },

        async doApplyStar(payload, rootState) {
            const resp = await applyStarReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doResetPassword(payload) {
            payload.old = encryptPwd(payload.old)
            payload.new = encryptPwd(payload.new)
            const resp = await resetPasswordReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    Toast.info('密码修改成功')
                }
            })
        },

        async doForgetPassword(payload) {

            const resp = await forgetPasswordReq(payload)

            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    Toast.info('密码重置成功')
                }
            })
        },

        async doChangeName(payload) {
            dispatch.global.showLoading()
            const resp = await changeNameReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    const uid = localStorage.getItem('userid')
                    Toast.info('修改成功', 1)
                    dispatch.user.fetchUserDetail({uid,})
                }
            })
        },

        async doFetchOfficialNotice(payload) {
            const resp = await fetchOfficialNoticeReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doFetchSystemInfo(payload) {
            const resp = await fetchSystemInfoReq(payload)
            handleResp(resp, dispatch, (data) => {
            })
        },

        async doChangeAvatar(payload) {
            const resp = await uploadAvatarReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok) {
                    Toast.info('更换成功')
                    let uid = LocalStorageService.get('userid')
                    this.fetchUserDetail({uid,})
                }
            })
        },

        async doBuyVip(payload) {
            const resp = await buyVipReq(payload)
            handleResp(resp, dispatch, (data) => {
                const addExp = data.ok.addexp
                const info = <div>
                    <p>续费成功</p>
                    <p>经验+{addExp}</p>
                </div>
                Toast.info(info, 1)
                dispatch.user.fetchUserDetail({uid,})
            })
        },

        async doFeedback(payload) {
            const resp = await feedbackReq(payload)
            handleResp(resp, dispatch, (data) => {
                if (data.ok === 1) {
                    Toast.info('反馈成功')
                }
            })
        },

        async doFetchFeedbackList(payload) {
            payload.uid = uid
            const resp = await feedbackListReq(payload)
            handleResp(resp, dispatch, (data) => {
                dispatch.user.setFeedbackList(data.ok)
            })
        },

        async doWechatPay(payload) {
            let {
                uid,
                style,
                redirect,
                mark,
            } = payload

            let params = {uid, style,mark,}
            if (magic || uid === '87a2308b-9837-4c1e-a8ce-0f002c86214f') {
                params.secret = 'ohyeah!retou'
            }

            const resp = await wechatReq(params)
            // const goback = location.href
            handleResp(resp, dispatch, (data) => {
                const href = data.mweb_url.Text
                const dealno = data.dealno
                // const wxdealno = data.ok
                // const redirect = encodeURIComponent(`http://www.youtoball.com:8080/wallet?dealno=${dealno}`)
                redirect += `&dealno=${dealno}`
                let redirectUrl = encodeURIComponent(redirect)
                const location = `${href}&redirect_url=${redirectUrl}`
                const a = document.createElement('a')
                a.setAttribute('href', location)
                const span = document.createElement('span')
                span.innerText = 'wx'
                a.appendChild(span)
                document.body.appendChild(a)
                // window.alert(document.referrer)
                setTimeout(() => {
                    a.click()
                    span.click()
                }, 1000)

            }) 
        },

        async doCheckWechatOrder(payload, rootState) {

            const resp = await checkWechatOrderReq(payload)

            const data = resp.data
            if (data.err === 331) {
                Toast.info('订单未支付')
            } else {
                handleResp(resp, dispatch, (data) => {

                    // const ok = data.ok
                    // const money = data.money
                    // const addexp = data.addexp
                    // const lv = data.lv
                    if (data.ok || data.ok === 0) {

                        const uid = LocalStorageService.get('userid')
                        dispatch.user.fetchUserDetail({uid,})


                        const {
                            style,
                        } = payload
                        const matchId = Number(payload.matchid)
                        if (Number(style) === 101) {
                            // this.props.doFetchGameAi({uid, matchId,})
                            dispatch.game.doFetchGameAi({uid, matchId,})
                        }
                        //
                        // // let toastInfo = Object.keys(data).map(key => {
                        // //     let p = <p>{key}:{data[key]}</p>
                        // //     return p
                        // // })
                        // let toastInfo
                        //
                        // if (style >= 1 && style <= 6) {
                        //     const addexp = data.addexp
                        //     toastInfo = <div><p>充值成功</p><p>经验+{addexp}</p></div>
                        // }
                        //
                        // if (style === 100) {
                        //     const addexp = data.ok.addexp
                        //     toastInfo = <div><p>开通会员成功</p><p>经验+{addexp}</p></div>
                        // }
                        //
                        // console.log(style)

                        //
                        // setTimeout(() => {
                        //     Toast.info(toastInfo, 2)
                        // }, 1000)
                        //
                        // if (style === 100) {
                        //     toastInfo = <div><p>开通会员成功</p><p>经验+{addexp}</p></div>
                        // }
                        //
                        // if (style === 101) {
                        //     toastInfo = <div><p>购买ai预测成功</p><p>经验+{addexp}</p></div>
                        // }
                        //
                        setTimeout(() => {
                            let toastInfo = <div><p>支付成功</p></div>
                            Toast.info(toastInfo, 2)
                        }, 1000)
                    }
                })
            }
        }
    }),
}
